// let index = require('./index');
let http = require('http');
let fs = require('fs');
let url = require('url');

let Browser = require('child_process')

const PORT = 3000;
let server = http.createServer();

server.on('request', (req, res) => {

    let pathName = url.parse(req.url).pathname;
    let ext = pathName.match(/(\.[^.]+|)$/)[0];

    switch (ext) {
        case '.js':
            fs.readFile('.' + req.url, 'utf-8', (err, data) => {
                if (err) {
                    throw err;
                }

                res.writeHead(200, {
                    'Content-Type': 'application/javascript'
                });
                res.write(data);
                res.end();
            })
            break;

        default:
            fs.readFile('./index.html', 'utf-8', (err, data) => {
                if (err) {
                    throw err;
                }

                res.writeHead(200, {
                    'Content-Type': 'text/html'
                });
                res.write(data);
                res.end();
            })
            break;
    }
})
server.listen(PORT);

// 终端打印如下信息
console.log('Server running at http://127.0.0.1:' + PORT);
//  调用默认浏览器打开页面
Browser.exec('start http://127.0.0.1:' + PORT);